package com.mgface.framework.https;

import org.apache.catalina.connector.Connector;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.SocketUtils;

/**
 * 生成内嵌的HTTPS访问
 * 
 * @author user
 *
 */
@Configuration
public class HttpTomcatEmbeddedServletContainerFactory {
	private static final Logger log = LogManager.getLogger(HttpTomcatEmbeddedServletContainerFactory.class);
	@Value("${system.http-port:8888}")
	private int port;

	@Bean
	public Integer port() {
		if (port == 0) {
			port = SocketUtils.findAvailableTcpPort();
		}
		log.info("获取有效的端口值:{}", port);
		return port;
	}

	@Bean
	public EmbeddedServletContainerFactory servletContainer() {
		TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
		tomcat.addAdditionalTomcatConnectors(createStandardConnector());
		return tomcat;
	}

	private Connector createStandardConnector() {
		Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
		connector.setPort(port());
		connector.setAsyncTimeout(5000L);
		connector.addLifecycleListener((e) -> {
			log.info("生命周期阶段:{}", e.getType());
		});
		return connector;
	}
}
